﻿using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsynShowDialog
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            this.InitializeComponent();
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            /*var result = */this.ShowDialogAsync();
            //for (var n = this.progressBar1.Minimum; n <= this.progressBar1.Maximum; n++)
            //{
            //    this.progressBar1.Value = n;
            //    Thread.Sleep(20);
            //}
            MessageBox.Show(@"Here we go!");
        }

        delegate DialogResult GetDialogResultCallback();

        private DialogResult DoShowDialog()
        {
            return new Form2().ShowDialog(this); 
        }

        private async void ShowDialogAsync()
        {
            await Task.Run(() =>
            {
                if (this.InvokeRequired)
                {
                    GetDialogResultCallback callback = this.DoShowDialog;
                    return (DialogResult)this.Invoke(callback);
                }
                
                return new Form2().ShowDialog(this);
            });
        }
    }
}
